package ec.fugu.amf;

import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import ec.fugu.util.ObserverInterface;

public class AmfClientWrapper implements ObserverInterface {
    private boolean _needAuth = false;

    private AmfClientThread _requestThread = null;
    private int _returnCode = ObserverInterface.NEW;
	private AmfMessage _response = null;
    private AmfClient _client=null;
    private String _method=null;
    private Object[] _params=null;
    private long _startTime=0;
    private long _finishTime=0;
    private int _timeout=3000;
    private int _updateInterval=100;


    public AmfClientWrapper(AmfClient client, String method, Object[] params, boolean needAuth, int timeout){
    	_client = client;
    	_method = method;
    	_params = params;
    	_needAuth = needAuth;
    	_timeout = timeout;
    }
    
    public Object[] execute() {
        _requestThread = new AmfClientThread(_client, _method, _params, this, _needAuth);
        _requestThread.start();
        _startTime = System.currentTimeMillis();
        _finishTime = _startTime + _timeout;
    	while(System.currentTimeMillis()< _finishTime){
    		if(_returnCode!=ObserverInterface.NEW)
    			break;
            try {
                Thread.sleep(_updateInterval);
            } catch (InterruptedException e) {
            }
    	}
		if(_returnCode!=ObserverInterface.NEW){
            if ( _requestThread != null ) {
                if ( _requestThread.isAlive() ) {
                    _requestThread.stop();
                    // This will send us a 'failure' notification
                }
            }
		}
        return new Object[]{new Integer(_returnCode), _response};
    }
    
    public void processStatusUpdate(final int status, final String statusString) {
        UiApplication.getUiApplication().invokeLater(new Runnable() {
            public void run () {
            	//Do nothing
            }
        });
    }

    public void processResponse(final AmfMessage response) {
        _returnCode = ObserverInterface.OK;
        _response = response;
    }

    public void processError(int errorCode, final String errorMessage) {
        _returnCode = errorCode;
        UiApplication.getUiApplication().invokeLater(new Runnable() {
            public void run () {
                Dialog.alert("Error:!\n" + errorMessage);
            }
        });
    }

	public void processResponse(String response) {
		// TODO Auto-generated method stub
		
	}

}
